package com.xhy.documents_collection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.cache.UserCache;
import com.xhy.documents_collection.entity.PO.email.EmailSetting;
import com.xhy.documents_collection.entity.PO.task.TaskRecord;
import com.xhy.documents_collection.entity.PO.task.TaskTimingRecord;
import com.xhy.documents_collection.mapper.EmailSettingMapper;
import com.xhy.documents_collection.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhy.documents_collection.service.async.AsyncService;
import com.xhy.documents_collection.service.task.TaskRecordService;
import com.xhy.documents_collection.service.task.TaskTimingRecordService;
import com.xhy.documents_collection.utils.R;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2023-03-04
 */
@Service
public class EmailSettingServiceImpl extends ServiceImpl<EmailSettingMapper, EmailSetting> implements EmailSettingService {


    @Resource
    AsyncService asyncService;


    @Override
    public R getByUserId() {
        Integer userId = UserHolder.get();
        EmailSetting emailSetting = getOne(new LambdaQueryWrapper<EmailSetting>().eq(EmailSetting::getUserId, userId));
        if (ObjectUtils.isEmpty(emailSetting)){
            emailSetting = new EmailSetting();
            emailSetting.setUserId(userId);
            emailSetting.setState(false);
            save(emailSetting);
        }
        return R.ok().data("data",emailSetting);
    }

    @Override
    public R update(EmailSetting emailSetting) {
        emailSetting.setUserId(UserHolder.get());
        emailSetting.setState(false);
        updateById(emailSetting);
        return R.ok().message("修改成功,请尝试校验邮箱是否能够使用").data("data",emailSetting);
    }


    @Override
    public R testSend() {
        Integer userId = UserHolder.get();
        EmailSetting emailSetting = getOne(new LambdaQueryWrapper<EmailSetting>().eq(EmailSetting::getUserId, userId));
        if (ObjectUtils.isEmpty(emailSetting)){
            return R.error().message("邮箱配置为空");
        }
        asyncService.sendTestEmail(emailSetting);
        return R.ok().message("发送中,如果发送成功则自己会收到邮箱,如果没有收到则配置失败,请重新配置");
    }

    @Override
    public JavaMailSenderImpl createMessage(EmailSetting emailSetting) {
        //创建实例
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        //设置发送的服务器（这里的属性 qq和网易的不一样）qq：smtp.qq.com   网易：smtp.126.com
        sender.setHost(emailSetting.getHost());
        //当前发送人邮箱（也就是自己）
        String sendUserName = emailSetting.getUserName();
        sender.setUsername(sendUserName);
        //授权码 （不是邮箱密码  是上面咱们的准备工作获取的那个码）
        sender.setPassword(emailSetting.getPassword());
        sender.setPort(465);
        Properties p = new Properties();
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.ssl", "true");
        p.setProperty("mail.smtp.socketFactory.port", emailSetting.getHost());
        p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        p.setProperty("mail.smtp.starttls.enable", "true");
        p.setProperty("mail.smtp.starttls.required", "true");
        sender.setJavaMailProperties(p);
        //解决-发送邮件时附件名太长会被截取掉或者中文乱码问题
        System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
        return sender;
    }




    @Override
    public boolean sendTaskFile(TaskTimingRecord taskTimingRecord, String filePath) {
        String content = taskTimingRecord.getContent();
        Integer userId = taskTimingRecord.getUserId();
        EmailSetting emailSetting = getOne(new LambdaQueryWrapper<EmailSetting>().eq(EmailSetting::getUserId, userId));
        // 发送
        JavaMailSenderImpl sender = createMessage(emailSetting);
        String from = emailSetting.getUserName();
        String to = taskTimingRecord.getReceive();
        MimeMessage message = sender.createMimeMessage();
        //这里的utf-8解决 邮件 内容乱码
        //使用MimeMessageHelper帮助类，并设置multipart多部件使用为true
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message );
            if (!ObjectUtils.isEmpty(filePath)){
                String attachmentName = taskTimingRecord.getSubject() +".zip";
                helper  = new MimeMessageHelper(message, true);
                helper.addAttachment(attachmentName,new File(filePath));
            }
            //当前发送人邮箱（也就是自己）
            helper.setFrom(from);
            //发送到的邮箱地址
            helper.setTo(to);
            //邮件主题、标题
            helper.setSubject(taskTimingRecord.getSubject());
            //内容
            helper.setText(content);
            sender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void testSend(String from,String to,Integer userId) {
        EmailSetting emailSetting = getOne(new LambdaQueryWrapper<EmailSetting>().eq(EmailSetting::getUserId, userId));
        // 发送
        JavaMailSenderImpl sender = createMessage(emailSetting);
        String sendUserName = emailSetting.getUserName();
        String receiveUserName = from;
        MimeMessage message = sender.createMimeMessage();
        //这里的utf-8解决 邮件 内容乱码
        //使用MimeMessageHelper帮助类，并设置multipart多部件使用为true
        try {
            MimeMessageHelper helper  = new MimeMessageHelper(message, true);
            //当前发送人邮箱（也就是自己）
            helper.setFrom(sendUserName);
            //发送到的邮箱地址
            helper.setTo(to);
            //邮件主题、标题
            helper.setSubject("测试邮箱");
            //内容
            sender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void send(EmailSetting emailSetting, String content) {
        JavaMailSenderImpl sender = createMessage(emailSetting);
        MimeMessage message = sender.createMimeMessage();
        String from = emailSetting.getUserName();
        String to = from;

        //这里的utf-8解决 邮件 内容乱码
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true, "utf-8");
            //当前发送人邮箱（也就是自己）
            helper.setFrom(from);
            //发送到的邮箱地址
            helper.setTo(to);
            //邮件主题、标题
            helper.setSubject("定时任务状态提示");
            //内容
            helper.setText(content);
            sender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
